<?php
/**
 * Created by IntelliJ IDEA.
 * User: lee
 * Date: 2018/2/5
 * Time: 下午3:15
 */

namespace Biz\service\trade;


use Biz\model\trade\Cart as mCart;

use Biz\module\Classes\Cart as clsCart;
use Biz\module\Classes\wiki\SpuToWiki;
use Biz\service\ShopGoodsOperator;
use Doraemon\tools\HhzClient;
use Doraemon\tools\Log as tLog;
use Doraemon\pockets\constInterface\AppType;
use Biz\model\ShopFavorite as mShopFavorite;
/**
 * @deprecated
 */
class Cart implements AppType
{
    protected static $furnitureMap = [];

    /**
     * 购物车日志
     * @param string $title 日志标识
     * @param array $params 存储数据
     */
    private static function log($title, $params)
    {
        tLog::cart_basic_warning('购物车日志::' . $title, $params);
    }

    /**
     * 是否是节选来源
     * @param int $appType app类型
     * @return bool
     */
    public static function getAppSource($appType)
    {
        return $appType == AppType::APPTYPE_PARAGRAPH_MINIPROGRAM ? AppType::APPTYPE_PARAGRAPH_MINIPROGRAM : 0;
    }

    /**
     * 用户/游客添加购物车
     * @param mixed $uid
     * @param int $skuId
     * @param int $buyNum
     * @param int $appType app类型
     * @return mixed
     * @throws \Exception
     */
    public static function addToCart($uid, $skuId, $buyNum, $appType = 0)
    {
        //判断SKU是否有效  商品及SKU维度的状态是否正确
        //判断sku基础库存
        //判断SKU 是否限购，如果限购则判断限购是否符合规范
        //计算价格 如果在限时抢活动进行时
        //购物车中商品价格的计算

        try {
            $appSource = self::getAppSource($appType);

            return mCart::action(function () use ($uid, $skuId, $buyNum, $appSource) {
                return self::getClsCart($uid)->addToCart($uid, $skuId, $buyNum, $appSource);
            });

        } catch (\Exception $e) {

            self::log('用户加购物车失败', [
                'uid' => $uid,
                'sku_id' => $skuId,
                'buy_num' => $buyNum,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);
            if ($e->getCode() == self::getClsCart($uid)::ERROR_CODE_FORBIDDEN) {
                throw new \Exception('添加购物车失败');
            } else {
                throw $e;
            }
        }
    }

    /**
     * 从购物车中删除sku或移入收藏
     * @param mixed $uid 用户id
     * @param array $skuIds 货品id集合
     * @param int $toFav 移入收藏开关
     * @param int $appType app类型
     * @return mixed
     * @throws \Exception
     */
    public static function delSku($uid, $skuIds = [], $toFav = 0, $appType = 0)
    {
        //从购物车列表中删除SKU
        try {
            $appSource = self::getAppSource($appType);

            if ($toFav > 0) {
                $title = '收藏购物车SKU成功';
            } else {
                $title = '删除购物车SKU成功';
            }

            $result = self::getClsCart($uid)->delCart($uid, $skuIds, $appSource, 'cart', $toFav);

            tLog::info($title, ['uid' => $uid,'sku_ids' => $skuIds,'toFav'=>$toFav]);

            return $result;
        } catch (\Exception $e) {
            self::log('删除|收藏购物车SKU失败', [
                'uid' => $uid,
                'toFav' => $toFav,
                'appType' => $appType,
                'sku_ids' => $skuIds,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);
            throw $e;
        }

    }

    /**
     * 购物车列表
     * @param mixed $uid
     * @param array $skuIds
     * @param string $areaCode
     * @param int $appType
     * @return mixed
     * @throws \Exception
     */
    public static function cartList($uid, $skuIds = [], $areaCode = '', $appType = 0)
    {
        try {
            $versionBool  = version_compare(HhzClient::getClientVersion(), '3.13.0', '>=');
            $versionBool465 = version_compare(HhzClient::getClientVersion(), '4.6.5', '>=');
            $appTypeBool = in_array($appType, [AppType::APPTYPE_ANDROID, AppType::APPTYPE_IOS]);
            $appSource = self::getAppSource($appType);
            if ($versionBool && $appTypeBool) {
                if($versionBool465) {
                    //住友津贴
                    $result = self::getClsCart($uid)->cartListVersion461($uid, $skuIds, $areaCode, $appSource, $appType);

                } else {
                    $result = self::getClsCart($uid)->cartListVersion($uid, $skuIds, $areaCode, $appSource, $appType);
                }

            } else {
                $result = self::getClsCart($uid)->cartList($uid, $skuIds, $areaCode, $appSource, $appType);
            }
            return $result;
        } catch (\Exception $e) {
            self::log('用户获取购物车列表失败', [
                'appType' => $appType,
                'version' => HhzClient::getClientVersion(),
                'uid' => $uid,
                'sku_ids' => $skuIds,
                'area_code' => $areaCode,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);
            throw $e;
        }
    }

    /**
     * 增减购买数
     * @param $uid
     * @param $skuId
     * @param int $buyNum
     * @param int $currentBuyNum
     * @param int $appType
     * @return null
     * @throws \Exception
     */
    public static function updateBuyNum($uid, $skuId, $buyNum = 1, $currentBuyNum = 0, $appType = 0)
    {
        //走添加SKU到购物车的接口
        try {
            $appSource = self::getAppSource($appType);

            $result = mCart::action(function () use ($uid, $skuId, $buyNum, $currentBuyNum, $appSource) {
                $result = self::getClsCart($uid)->updateBuyNum($uid, $skuId, $buyNum, $currentBuyNum, $appSource);

                return $result;
            });

            if (empty($result)) {
                return null;
            }

            return $result;
        } catch (\Exception $e) {

            tLog::cart_basic_warning('更新购物车sku数量失败', [
                'uid' => $uid,
                'sku_id' => $skuId,
                'buy_num' => $buyNum,
                'current_buy_num' => $currentBuyNum,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);

            throw $e;
        }
    }

    /**
     * 购物车统计信息
     * @param $uid
     * @param int $appType
     * @return array
     */
    public static function totalSum($uid, $appType = 0){
        $appSource = self::getAppSource($appType);

        $data = self::getClsCart($uid)->totalSum($uid, $appSource);

        return $data;
    }

    /**
     * 修改购物车中SKU信息
     * @param $uid
     * @param $oldSkuId
     * @param $newSkuId
     * @param int $appType
     * @return array
     * @throws \Exception
     */
    public static function changeSku($uid, $oldSkuId, $newSkuId, $appType = 0)
    {
        //更新旧的SKU信息
        //把新的skuID增加到购物车中
        try {
            $appSource = self::getAppSource($appType);

            $result = mCart::action(function () use ($uid, $oldSkuId, $newSkuId, $appSource) {
                $result = self::getClsCart($uid)->changeSku($uid, $oldSkuId, $newSkuId, $appSource);
                return $result;
            });
            return $result;
        } catch (\Exception $e) {
            self::log('更换购物车中SKU信息失败', [
                'uid' => $uid,
                'old_sku_id' => $oldSkuId,
                'new_sku_id' => $newSkuId,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);

            throw $e;
        }
    }

    /**
     * 游客购物车迁到用户购物车
     * @param $vid
     * @param $uid
     * @param $appType
     * @return mixed
     */
    public static function cartvToCart($vid, $uid, $appType){

        try {
            $appSource = self::getAppSource($appType);

            $result = mCart::action(function () use ($vid, $uid, $appSource) {

                $result = (new clsCart())->cartvToCart($vid, $uid, $appSource);

                return $result;
            });

            tLog::cart_cartvtocart_info('游客购物车迁移到用户购物车', [
                'uid'        => $uid,
                'vid' => $vid,
            ]);

            return $result;

        } catch (\Exception $e) {

            tLog::cart_cartvtocart_warning('游客购物车迁移到用户购物车', [
                'uid'        => $uid,
                'vid' => $vid,
                'e_msg'      => $e->getMessage(),
                'e_file'     => $e->getFile(),
                'e_line'     => $e->getLine()
            ]);

        }
    }

    /**
     * 根据用户id获取实例
     * @param mixed $uid 用户id
     * @return \Biz\module\Classes\Cart
     */
    public static function getClsCart($uid)
    {
        if ($uid > 0) {
            $model = (new clsCart());
        } else {
            $model = (new clsCart())->setVirtual();
        }
        return $model;
    }

    /**
     * 购物车历史数据转收藏
     * @param mixed $uid 用户id
     * @return mixed
     */
    public static function cartToFav($uid)
    {
        $errors = [];
        $goodsIds = [];
        $list = [];
        $changeCount = 0;
        try {
            //查询用户购物车数据
            $list = mCart::select('*', [
                'uid' => $uid,
                'status' => [mCart::STATUS_FAIL, mCart::STATUS_ACTIVE]
            ]);

            //查询商品和wiki的映射
            $goodsIds = empty($list) ? [] : array_column($list, 'goods_id');
            $map = empty($goodsIds) ? [] : SpuToWiki::getRelateWikiMapByGoodsIds($goodsIds);

            //把有映射的wiki列表转为收藏
            if ($list) {
                foreach ($list as $v) {
                    try {
                        if (isset($map[$v['goods_id']])) {
                            ShopGoodsOperator::favorite($uid, $map[$v['goods_id']], mShopFavorite::TYPE_WIKI, $v['app_source']);
                        } else {
                            ShopGoodsOperator::favorite($uid, $v['goods_id'], mShopFavorite::TYPE_GOODS, $v['app_source']);
                        }
                        $changeCount ++;
                    } catch (\Exception $e) {
                        $errors[] = [
                            'file' => $e->getFile(),
                            'line' => $e->getLine(),
                            'message' => $e->getMessage(),
                        ];
                        continue;
                    }
                }
            }
        } catch (\Exception $e) {
            $errors[] = [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'message' => $e->getMessage(),
            ];
        }
        self::log('购物车历史数据转收藏', compact('uid', 'errors', 'goodsIds'));
        return $changeCount;
    }

}